package com.javastar.common.utils;

import cn.hutool.json.JSONUtil;
import com.javastar.common.enums.TokenEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * jwt工具类
 *
 * @author zxx
 * @date 2023/7/23
 */
public class JwtUtil {

    /**
     * 根据id生成token
     * @param o
     * @param tokenEnum
     * @return
     */
    public static String generateToken(Object o, TokenEnum tokenEnum) {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + tokenEnum.getExpireTime());

        return Jwts.builder()
                .setSubject(JSONUtil.toJsonStr(o))
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, tokenEnum.getSecretKey())
                .compact();
    }

    public static String generateToken(Long id, TokenEnum tokenEnum) {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + tokenEnum.getExpireTime());

        return Jwts.builder()
                .setSubject(String.valueOf(id))
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS256, tokenEnum.getSecretKey())
                .compact();
    }

    /**
     * 从token中获取id
     * @param tokenEnum
     * @return
     */
    public static Long getId(String token, TokenEnum tokenEnum) {
        Claims claims = Jwts.parser()
                .setSigningKey(tokenEnum.getSecretKey())
                .parseClaimsJws(token)
                .getBody();

        return Long.valueOf(claims.getSubject());
    }

    /**
     * 从token中获取bean
     * @param tokenEnum
     * @return
     */
    public static <T> T getBean(String token, TokenEnum tokenEnum, Class<T> clazz) {
        Claims claims = Jwts.parser()
                .setSigningKey(tokenEnum.getSecretKey())
                .parseClaimsJws(token)
                .getBody();

        return JSONUtil.toBean(claims.getSubject(), clazz);
    }

    /**
     * 校验token有效性
     * @param tokenEnum
     * @return true有效 false无效
     */
    public static boolean validateToken(String token, TokenEnum tokenEnum) {
        try {
            Date expirationDate = Jwts.parser()
                    .setSigningKey(tokenEnum.getSecretKey())
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration();

            return !expirationDate.before(new Date());
        } catch (Exception e) {
            return false;
        }
    }

}

